package io.flutter.eventbus;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.common.StandardMethodCodec;

import java.util.ArrayList;

public class EventBus {
    private BinaryMessenger binaryMessenger;

    private final  static ArrayList<Topic<Object>> topics = new ArrayList<>();

    public EventBus(BinaryMessenger binaryMessenger){
        this.binaryMessenger = binaryMessenger;
    }

    public <T> Topic<T> topic(String topicName){
        Topic<T> topic = (Topic<T>)topics.stream().filter(t -> t.name.equals(topicName)).findFirst().orElse(this.<T>create(topicName));
        topic.isClose = false;
        return topic;
    }

    private <T> Topic<Object> create(String topicName){
        MethodChannel methodChannel= new MethodChannel(binaryMessenger, topicName, new StandardMethodCodec(new StandardMessageCodec()));
        Topic<Object> topic = new Topic(methodChannel,topicName);
        topics.add(topic);
        methodChannel.setMethodCallHandler(topic);
        return  topic;
    }
}